package com.mvc.Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mvc.util.Action;
import com.mvc.util.Form;
import com.mvc.util.FullForm;
import com.mvc.util.ReflectAction;
import com.mvc.util.Beans;

public class MvcConfigServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7610634964421229446L;

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
    ServletContext sc = this.getServletContext();
    Map<String,Beans> mvcconfigmap= (Map<String, Beans>) sc.getAttribute("mvcconfigmap");
    String servletpath = request.getServletPath();
    String path = servletpath.split("\\.")[0];
    Beans xb = mvcconfigmap.get(path);
    Form form = FullForm.full(xb.getFormtype(), request);
    Action action = ReflectAction.reflectaction(xb.getActiontype());
    String forward = action.execute(request, response, form);
    String forwardpath=xb.getResult().get(forward);
    request.getRequestDispatcher(forwardpath).forward(request, response);;
	}

}
